package portlet.tonghop.backing;

import javax.faces.context.FacesContext;

import javax.portlet.ActionResponse;
import javax.portlet.PortletConfig;
import javax.portlet.PortletMode;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequest;
import javax.portlet.WindowState;

import portlet.tonghop.TongHop;
import portlet.tonghop.resource.TongHopBundle;

public class TongHopBacking {
    private String mPortletTitle;

    public String getPortletTitle() {
        if (mPortletTitle == null) {
            PortletRequest request = (PortletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
            PortletPreferences preferences = request.getPreferences();
            mPortletTitle = preferences.getValue(TongHop.PORTLETTITLE_KEY, getResource(TongHopBundle.PORTLETTITLE));
        }
        return mPortletTitle;
    }

    public String getPortletTitleLabel() {
        String resource = getResource(TongHopBundle.PORTLETTITLE);
        return resource;
    }

    public void setPortletTitle(String portletTitle) {
        mPortletTitle = portletTitle;
    }

    public String applyAction() throws Exception {
        PortletRequest request = (PortletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
        PortletPreferences preferences = request.getPreferences();
        preferences.setValues(TongHop.PORTLETTITLE_KEY, mPortletTitle.split(","));
        preferences.store();
        return null;
    }

    public String getApplyLabel() {
        String resource = getResource(TongHopBundle.APPLY_LABEL);
        return resource;
    }

    public String okAction() throws Exception {
        applyAction();
        ActionResponse response = (ActionResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
        response.setPortletMode(PortletMode.VIEW);
        response.setWindowState(WindowState.NORMAL);
        return null;
    }

    public String getOkLabel() {
        String resource = getResource(TongHopBundle.OK_LABEL);
        return resource;
    }

    private String getResource(String resourceKey) {
        PortletRequest request = (PortletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
        PortletConfig config = (PortletConfig)request.getAttribute("javax.portlet.config");
        return config.getResourceBundle(request.getLocale()).getString(resourceKey);
    }
}
